﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


using Lenovo.CFI.BLL.Sys;
using Lenovo.CFI.Web.Helper;
using Lenovo.CFI.Common.Sys;

namespace Lenovo.CFI.Web.VP
{
    public partial class CfgTeam : System.Web.UI.UserControl
    {
        TeamBl teamBl = new TeamBl();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindHelper.BindUser("Select...", "-1", null, this.DdlManagerAdd, this.DdlVPAdd, this.DdlManagerEdit, this.DdlVPEdit);

                BindTeams();
                

                MessageHelper.Prepare(this.Page, true);
            }
        }

        #region 绑定Team

        private void BindTeams()
        {
            List<Common.Sys.Team> teams = teamBl.GetTeam(null, null, null, null);
            BindHelper.BindTeam(this.DdlTeamEditUser, null, null, null, teams);

            this.RepTeam.DataSource = teams;
            this.RepTeam.DataBind();

            Common.Sys.Team currentTeam = null;
            if (ViewState["TeamID"] != null)
            {
                currentTeam = teams.Find(t => t.ID == (int)ViewState["TeamID"]);
            }
            if (currentTeam == null && teams.Count > 0)
                currentTeam = teams[0];

            if (currentTeam != null)
                BindTeam(currentTeam);

        }

        private void BindTeam(Common.Sys.Team team)
        {
            // 保存选择节点信息
            ViewState["TeamID"] = team.ID;


            // 组织信息
            this.TxtTitleEdit.Text = team.Title;
            this.DdlManagerEdit.ClearSelection();
            ListItem li = this.DdlManagerEdit.Items.FindByValue(team.Manager);
            if (li != null) li.Selected = true;
            this.DdlVPEdit.ClearSelection();
            li = this.DdlVPEdit.Items.FindByValue(team.VP);
            if (li != null) li.Selected = true;
            this.CbGddlEdit.Checked = team.GDDL;
            this.CbEnabledEdit.Checked = team.Enabled;            

            // 显示用户
            ViewState["usermethod"] = 1;
            this.BindUsers();
        }

        #endregion

        // 绑定用户
        private void BindUsers()
        {
            if ((int)ViewState["usermethod"] == 1)
            {
                this.GvUser.DataSource = new UserBl().GetUser(null, (int)ViewState["TeamID"], null, null, null, null);
            }
            else
            {
                this.GvUser.DataSource = new UserBl().GetUser(this.TxtItCode.Text, null, null, null, null, null);
            }
            this.GvUser.DataBind();
        }


        #region 显示详细信息


        protected void GvUser_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)    // 数据行
            {
                // 设置行号
                ((Literal)(e.Row.FindControl("LtrNo"))).Text = String.Format("{0}", e.Row.DataItemIndex + 1);

                User user = (User)e.Row.DataItem;

                if (!user.Enabled) e.Row.CssClass += " disabled";
            }
        }


        protected void TxtItCode_TextChanged(object sender, EventArgs e)
        {
            ViewState["usermethod"] = 2;

            this.GvUser.DataSource = new UserBl().GetUser(this.TxtItCode.Text, null, null, null, null, null);
            this.GvUser.DataBind();
        }




        User editUser = null;
        protected void GvUser_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "OpenEdit")
            {
                editUser = new UserBl().GetUserByItCode(e.CommandArgument.ToString());

                ViewState["ItCode"] = editUser.ItCode;

                this.TxtItCodeEditUser.Text = editUser.ItCode;
                this.TxtRealNameEditUser.Text = editUser.RealName;
                this.TxtPhoneEditUser.Text = editUser.Phone;

                this.DdlTeamEditUser.ClearSelection();
                ListItem li = this.DdlTeamEditUser.Items.FindByValue(editUser.TeamID.ToString());
                if (li != null) li.Selected = true;


                this.DdlLevelEditUser.ClearSelection();
                li = this.DdlLevelEditUser.Items.FindByValue(editUser.PermLevel.ToString());
                if (li != null) li.Selected = true;

                this.CbRolesEditUser.ClearSelection();
                foreach (string r in editUser.Roles)
                {
                    li = this.CbRolesEditUser.Items.FindByValue(r);
                    if (li != null) li.Selected = true;
                }

                this.DdlStatusEditUser.ClearSelection();
                this.DdlStatusEditUser.SelectedIndex = editUser.Enabled ? 0 : 1;                

                this.MpeEditUser.Show();
            }
        }


        #endregion

        #region 操作

        // 编辑
        protected void BtnSave_Click(object sender, EventArgs e)
        {
            Team team = teamBl.GetTeamByID((int)ViewState["TeamID"]);

            if (team == null)
            {
                #region 不存在

                MessageHelper.RegShowJSAjax(this.RepTeam, "Invalid Organ, not exist or removed!", this.Page);

                // 绑定组织
                this.BindTeams();
                this.UpUser.Update();

                #endregion
            }
            else
            {
                team.Title = this.TxtTitleEdit.Text;
                team.Manager = this.DdlManagerEdit.SelectedValue;
                team.VP = this.DdlVPEdit.SelectedValue;
                team.GDDL = this.CbGddlEdit.Checked;
                team.Enabled = this.CbEnabledEdit.Checked;

                try
                {
                    teamBl.EditTeam(team);
                }
                catch (ApplicationException aex)
                {
                    MessageHelper.RegShowJSAjax(this.BtnSave, aex.Message, this.Page);
                    return;
                }
                catch (Exception ex)            // Ajax无法使用默认异常处理程序处理异常
                {
                    ErrorHelper.ExceptionHanderForAjax(ex, this.BtnSave, this.Page);
                }

                this.BindTeams();
                MessageHelper.RegShowJSAjax(this.BtnSave, "Success!", this.Page);
                this.UpTeamList.Update();
            }
        }

        // 添加
        protected void BtnAddTeamSave_Click(object sender, EventArgs e)
        {
            Team team = new Team();
            team.Title = this.TxtTitleAdd.Text;
            team.Manager = this.DdlManagerAdd.SelectedValue;
            team.VP = this.DdlVPAdd.SelectedValue;
            team.GDDL = this.CbGddlAdd.Checked;
            team.Enabled = true;

            try
            {
                teamBl.AddTeam(team);
            }
            catch (ApplicationException aex)
            {
                MessageHelper.RegShowJSAjax(this.BtnAddTeamSave, aex.Message, this.Page);
                return;
            }
            catch (Exception ex)            // Ajax无法使用默认异常处理程序处理异常
            {
                ErrorHelper.ExceptionHanderForAjax(ex, this.BtnAddTeamSave, this.Page);
            }

            ViewState["TeamID"] = team.ID;


            this.BindTeams();

            MessageHelper.RegShowJSAjax(this.BtnAddTeamSave, "Success!", this.Page);

            this.UpTeamList.Update();
        }



        // 编辑用户
        protected void BtnEditUserSave_Click(object sender, EventArgs e)
        {
            UserBl userBl = new UserBl();

            string itcode = ViewState["ItCode"].ToString();

            try
            {
                User user = userBl.GetUserByItCode(itcode);

                user.Phone = this.TxtPhoneEditUser.Text;
                user.TeamID = Convert.ToInt32(this.DdlTeamEditUser.SelectedValue);
                user.PermLevel = Convert.ToInt32(this.DdlLevelEditUser.SelectedValue);
                user.Roles.Clear();
                foreach (ListItem role in this.CbRolesEditUser.Items)
                {
                    if (role.Selected)
                    {
                        user.Roles.Add(role.Value);
                    }
                }
                user.Enabled = (this.DdlStatusEditUser.SelectedIndex == 0);

                

                userBl.EditUser(user);

                ViewState["ItCode"] = null;

                MessageHelper.RegShowJSAjax(this.BtnEditUserSave, "Success!", this.Page);

                this.BindUsers();
            }
            catch (ApplicationException aex)
            {
                MessageHelper.RegShowJSAjax(this.BtnEditUserSave, aex.Message, this.Page);
            }
            catch (Exception ex)            // Ajax无法使用默认异常处理程序处理异常
            {
                ErrorHelper.ExceptionHanderForAjax(ex, this.BtnEditUserSave, this.Page);
            }
        }


        #endregion

        #region 显示区域

        private void SetTeamInfoVisibility(bool visible)
        {
            this.FsEdit.Visible = visible;
            this.FsUser.Visible = visible;
        }

        #endregion

        protected void RepTeam_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)    // 数据行
            {
                Team team = (Team)e.Item.DataItem;
                string title = team.Title;
                if (team.GDDL)
                    title += (" - " + team.Manager + ", " +team.VP);
                ((LinkButton)(e.Item.FindControl("BtnTeam"))).Text = team.Title;
            }
        }

        protected void RepTeam_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            Team team = teamBl.GetTeamByID(Convert.ToInt32(e.CommandArgument));

            if (team != null)
            {
                this.BindTeam(team);
            }
        }
    }
}